from framework.common.pt_logger import logger
from spider_module_loader import ModuleLoader
from spider_registry import initiator_registry
from util import eventWrapper

overridden_parameters = {
    "enableNotification": False
}


def processRequest(req, event=None, context=None):
    logger.info("started")
    logger.info("req: %s" % req)
    req["metadata"]["time"] = event["time"]
    spider_name = req["metadata"]["SpiderName"]
    print(f"spider_name: {spider_name}")
    initiator_name = req["metadata"]["InitiatorName"]
    print(f"initiator_name: {initiator_name}")
    if spider_name not in initiator_registry:
        raise Exception(f"spider {spider_name} is not registered, please check spider_registry.py if the {spider_name} was defined properly.")
    module_name = initiator_registry[spider_name][initiator_name]
    initiator_module = ModuleLoader(module_name=module_name, spider_name=spider_name)

    spider_lib = initiator_module.load()
    spider_lib.start_initiator(req.get("metadata"), req.get("payload"))


globals()['eventWrapper'].global_parameters = {**globals()['eventWrapper'].global_parameters, **overridden_parameters}
globals()['eventWrapper'].processRequest = processRequest
globals()['handler'] = eventWrapper.handler